package com.legendshop.openportal.sdk.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.legendshop.openportal.sdk.model.OpenResult;
import com.legendshop.openportal.sdk.model.constants.CommonConstants;
import com.legendshop.openportal.sdk.model.constants.CommonStatusEnum;

import java.lang.reflect.Type;

/**
 * @author jzh
 * @version 1.0.0
 * @title ConvertUtil
 * @date 2024/6/19 15:46
 * @description：转换工具
 */
public class ConvertUtil {

    private ConvertUtil() {}

    /**
     * 转换成OpenResult
     * @param jsonObject
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> OpenResult<T> convert2OpenResult(JSONObject jsonObject, Type clazz) {
        if (jsonObject == null) {
            return OpenResult.fail(CommonStatusEnum.UNABLE_ANALYZER);
        }

        // 新的响应封装
        if (jsonObject.containsKey(CommonConstants.SUCCESS)) {
            String status = jsonObject.getStr(CommonConstants.STATUS);
            String message = jsonObject.getStr(CommonConstants.MESSAGE);
            Boolean success = jsonObject.getBool(CommonConstants.SUCCESS);
            return new OpenResult<>(success, status, message, success ? toBean(jsonObject, CommonConstants.DATA, clazz) : null);
        }

        // 旧的响应封装
        if (jsonObject.containsKey(CommonConstants.CODE)) {
            Integer code = jsonObject.getInt(CommonConstants.CODE);
            if (code == 0) {
                return OpenResult.success(toBean(jsonObject, CommonConstants.DATA, clazz));
            } else {
                String message = jsonObject.getStr(CommonConstants.MESSAGE);
                return OpenResult.fail(code.toString(), message);
            }
        }

        // 没有响应封装
        return OpenResult.success(toBean(jsonObject, null, clazz));
    }

    /**
     * 转成对应的bean
     * @param data      响应转换的json对象
     * @param key       json内参数的key，如果需要转换成基本数据类型，则需要传这个值
     * @param clazz     响应类型
     * @return
     * @param <T>
     */
    public static <T> T toBean(JSONObject data, String key, Type clazz) {
        if (clazz.equals(Void.class) || data == null || data.isEmpty()) {
            return null;
        }

        if (StrUtil.isEmpty(key)) {
            return JSONUtil.toBean(data, clazz, false);
        }

        Object value = data.getObj(key);
        if (JSONUtil.isNull(value)) {
            return null;
        }

        return Convert.convertWithCheck(clazz, value, null, false);

//        JSONObject jsonObject = data.getJSONObject(key);
//        if (jsonObject == null) {
//            return null;
//        }
//        return jsonObject.toBean(clazz);
//
////        Object value = data.get(key);
////        if (JSONUtil.isNull(value)) {
////            return null;
////        }
////
////        return Convert.convert(clazz, value);
    }
}
